package cn.ekuma.epos.util;

import java.util.ArrayList;
import java.util.List;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;

public class AbstractRuleChecker<T> {
	public List<T> checkRuleIn(I_DataLogicSystem dlSystem,String ruleName,List<T> checkObjs){
		byte[] drlText = dlSystem.getResourceAsBinary("rule."+ruleName);
		List<T> retObjs=new ArrayList<T>();
		if (drlText != null) {
			KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
			kbuilder.add(ResourceFactory.newByteArrayResource(drlText),ResourceType.DRL);
			KnowledgeBuilderErrors errors = kbuilder.getErrors();
			if (errors.size() > 0) {
				String messsage="";
				for (KnowledgeBuilderError error : errors) {
					messsage=messsage+error.getMessage()+"\n";
				}
				return retObjs;
			}
			KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
			kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
			
			StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
			// go !
			for(T obj:checkObjs)
			   ksession.insert(obj);
			ksession.insert(retObjs);
			ksession.fireAllRules();
		}
		return retObjs;
	}
}
